package com.sumer.psychology.common;

import com.sumer.psychology.common.media.GsonMessageBodyHandler;
import com.sumer.psychology.common.resource.ResourceApplication;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.external.ExternalTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.junit.MockServerRule;
import org.mockserver.matchers.Times;
import org.mockserver.model.Delay;

import javax.ws.rs.core.Application;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.concurrent.TimeUnit;

import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;

/**
 * User: zhenguang.zhu
 * Date: 2014/9/15
 * Time: 13:35
 */
public abstract class ResourceTestCase extends JerseyTest {
    @Rule
    public MockServerRule mockServerRule = new MockServerRule(8080, this);

    @BeforeClass
    public static void staticSetUp() {
        System.setProperty("jersey.config.test.container.port", "9966");
    }

    protected void mockStudent(String userId) {
        final String requestPath = String.format("/edu/user/%s", userId);
        final String responseBody = String.format("{user_id: '%s', user_lnm: 'zhu', user_tp: 5}", userId);

        new MockServerClient("localhost", 8080)
                .when(request()
                        .withMethod("GET")
                        .withPath(requestPath), Times.exactly(1))
                .respond(response()
                        .withStatusCode(200)
                        .withBody(responseBody)
                        .withDelay(new Delay(TimeUnit.SECONDS, 1)));
    }

    protected void mockUserId(String uId, String uIdPk) {
        final String requestPath = String.format("/login/getid/%s/%s", uId, uIdPk);

        new MockServerClient("localhost", 8080)
                .when(request()
                        .withMethod("GET")
                        .withPath(requestPath), Times.exactly(1))
                .respond(response()
                        .withStatusCode(200)
                        .withBody("1")
                        .withDelay(new Delay(TimeUnit.SECONDS, 1)));
    }

    @Override
    protected Application configure() {
        return new ResourceApplication();
    }

    @Override
    protected URI getBaseUri() {
        return UriBuilder.fromUri(super.getBaseUri()).path("sumer/api/v1").build();
    }

    @Override
    protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
        return new ExternalTestContainerFactory();
    }

    @Override
    protected void configureClient(ClientConfig config) {
        config.register(GsonMessageBodyHandler.class);
    }
}
